﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using OnlineBookstore.Models;

namespace OnlineBookstore.Controllers
{
    public class BookDetailsInfoController : Controller
    {
        private BookcityEntities db = new BookcityEntities();

        // GET: BookDetailsInfo
        [HttpGet]
        public ActionResult Index(int page = 1, int pageSize = 10, string category = "all")
        {
            // 检查 Session 逻辑
            var x = Convert.ToInt32(Session["Id"]);
            var data = db.CapitalAdvance.FirstOrDefault(m => m.ShopId == x);
            if (data == null)
            {
                CapitalA(x); // 你的自定义方法
            }

            // 构建基础查询
            IQueryable<BookDetailsInfo> query = db.BookDetailsInfo;

            // 添加分类筛选条件
            if (!string.IsNullOrEmpty(category) && category != "all")
            {
                query = query.Where(b => b.Booksort == category);
            }

            // 分页逻辑
            var totalCount = query.Count();
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
            page = Math.Max(1, Math.Min(page, totalPages));

            var books = query
                       .OrderBy(b => b.Id)
                       .Skip((page - 1) * pageSize)
                       .Take(pageSize)
                       .ToList();

            // 将分页和分类信息传递给视图
            ViewBag.CurrentPage = page;
            ViewBag.TotalPages = totalPages;
            ViewBag.PageSize = pageSize;
            ViewBag.TotalCount = totalCount;
            ViewBag.CurrentCategory = category; // 新增当前分类

            return View(books);
        }

        public void CapitalA(int Id)
        {
            var ca = new CapitalAdvance();
            ca.Balance = 0;
            ca.ReChargeAmount = 0;
            ca.ShopId = Id;
            if (ModelState.IsValid)
            {
                db.CapitalAdvance.Add(ca);
                db.SaveChanges();
            }

        }
        [HttpGet]
        public ActionResult Actions(int Id)
        {
            var ID = Convert.ToInt32(Session["Id"]);
            var x = db.CapitalAdvance.Where(m => m.ShopId == ID).FirstOrDefault();
            if (x != null)
            {
                Session["x"] = x.Balance;
            }
            else
            {
                Session["x"] = 00;

            }
            var data = db.shopInfo.Where(m => m.Id == Id).FirstOrDefault();
            return View(data);
        }
        [HttpPost]
        public ActionResult GetBook(string Name)
        {
            var data = db.BookDetailsInfo.Where(m => m.Booksort == Name).ToList();
            return View(data.ToList());

        }
        [HttpGet]
        public ActionResult GetBook()
        {
            return View();
        }




        // GET: BookDetailsInfo/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            BookDetailsInfo bookDetailsInfo = db.BookDetailsInfo.Find(id);
            if (bookDetailsInfo == null)
            {
                return HttpNotFound();
            }
            return View(bookDetailsInfo);
        }

        // GET: BookDetailsInfo/Create
        public ActionResult Create()
        {
            // 确保初始化了所有必要数据
            var model = new BookDetailsInfo();

            // 如果有下拉列表数据需要初始化
            ViewBag.BooksortList = new SelectList(new List<string> { "文学", "科技", "历史", "教育" });

            return View(model); // 明确传递新创建的模型
        }


        // POST: BookDetailsInfo/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(BookDetailsInfo bookDetailsInfo)
        {
            if (bookDetailsInfo == null)
            {
                throw new NullReferenceException("请输入信息");
            }
            bookDetailsInfo.BookCode = "CD" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (ModelState.IsValid)
            {
                db.BookDetailsInfo.Add(bookDetailsInfo);
                db.SaveChanges();
                return RedirectToAction("GetBookList");
            }

            return View(bookDetailsInfo);
        }

        // GET: BookDetailsInfo/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            BookDetailsInfo bookDetailsInfo = db.BookDetailsInfo.Find(id);
            if (bookDetailsInfo == null)
            {
                return HttpNotFound();
            }
            return View(bookDetailsInfo);
        }

        // POST: BookDetailsInfo/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]

        public ActionResult Edit(BookDetailsInfo bookDetailsInfo)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    // 记录模型验证错误
                    var errors = ModelState.Where(x => x.Value.Errors.Any())
                                         .Select(x => $"{x.Key}: {string.Join(", ", x.Value.Errors.Select(e => e.ErrorMessage))}");
                    System.Diagnostics.Debug.WriteLine("模型验证错误: " + string.Join("; ", errors));

                    return View(bookDetailsInfo);
                }

                var existingBook = db.BookDetailsInfo.Find(bookDetailsInfo.Id);
                if (existingBook == null)
                {
                    ModelState.AddModelError("", "要修改的书籍不存在或已被删除");
                    return View(bookDetailsInfo);
                }

                // 只更新允许修改的字段
                existingBook.BookName = bookDetailsInfo.BookName;
                existingBook.BookAuthor = bookDetailsInfo.BookAuthor;
                existingBook.Bookpress = bookDetailsInfo.Bookpress;
                existingBook.BookPrice = bookDetailsInfo.BookPrice;
                existingBook.Bookcover = bookDetailsInfo.Bookcover;
                existingBook.Booksort = bookDetailsInfo.Booksort;

                db.SaveChanges();

                TempData["SuccessMessage"] = "书籍信息更新成功！";
                return RedirectToAction("GetBookList");
            }
            catch (DbEntityValidationException ex)
            {
                // 处理数据库验证错误
                var errorMessages = ex.EntityValidationErrors
                                   .SelectMany(x => x.ValidationErrors)
                                   .Select(x => $"{x.PropertyName}: {x.ErrorMessage}");

                foreach (var error in errorMessages)
                {
                    ModelState.AddModelError("", error);
                }

                return View(bookDetailsInfo);
            }
            catch (Exception ex)
            {
                // 记录未处理的异常
                System.Diagnostics.Debug.WriteLine("未处理异常: " + ex.Message);

                ModelState.AddModelError("", "保存时发生错误，请重试");
                return View(bookDetailsInfo);
            }
        }
        // GET: BookDetailsInfo/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            BookDetailsInfo bookDetailsInfo = db.BookDetailsInfo.Find(id);
            if (bookDetailsInfo == null)
            {
                return HttpNotFound();
            }
            return View(bookDetailsInfo);
        }

        // POST: BookDetailsInfo/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            BookDetailsInfo bookDetailsInfo = db.BookDetailsInfo.Find(id);
            db.BookDetailsInfo.Remove(bookDetailsInfo);
            db.SaveChanges();
            return RedirectToAction("GetBookList");

        }


        public ActionResult GetBooksByCategory(string category)
        {
            // 如果是"全部图书"，获取所有书籍
            if (category == "all")
            {
                var allBooks = db.BookDetailsInfo.ToList();
                return PartialView("_BookListPartial", allBooks);
            }

            // 否则按分类筛选
            var filteredBooks = db.BookDetailsInfo.Where(b => b.Booksort == category).ToList();
            return PartialView("_BookListPartial", filteredBooks);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        public ActionResult GetBookList(int page = 1, int pageSize = 10)
        {
            // 获取总记录数
            var totalCount = db.BookDetailsInfo.Count();

            // 计算总页数
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

            // 确保请求的页码在有效范围内
            page = Math.Max(1, Math.Min(page, totalPages));

            // 获取分页数据
            var books = db.BookDetailsInfo
                         .OrderBy(b => b.Id) // 按ID排序，你可以根据需要修改排序字段
                         .Skip((page - 1) * pageSize)
                         .Take(pageSize)
                         .ToList();

            // 将分页信息传递给视图
            ViewBag.CurrentPage = page;
            ViewBag.TotalPages = totalPages;
            ViewBag.PageSize = pageSize;
            ViewBag.TotalCount = totalCount;

            return View(books);
        }



        public ActionResult GetBookId(int Id)
        {

            var data = db.BookDetailsInfo.Where(m => m.Id == Id).FirstOrDefault();
            return View(data);
        }
        // 获取搜索建议
        [HttpGet]
        public ActionResult SearchBooks(string keyword)
        {
            // 基本搜索逻辑
            var results = db.BookDetailsInfo
                .Where(b => b.BookName.Contains(keyword) ||
                           b.BookAuthor.Contains(keyword) ||
                           b.Bookpress.Contains(keyword))
                .ToList();

            // 处理AJAX请求
            if (Request.IsAjaxRequest())
            {
                return PartialView("_BookListPartial", results);
            }

            // 处理普通请求
            return View(results);
        }

        [HttpGet]
        public JsonResult GetSearchSuggestions(string keyword)
        {
            try
            {
                var suggestions = db.BookDetailsInfo
                    .Where(b => b.BookName.Contains(keyword) ||
                               b.BookAuthor.Contains(keyword) ||
                               b.Bookpress.Contains(keyword))
                    .Select(b => new {
                        BookName = b.BookName,
                        Author = b.BookAuthor,
                        Press = b.Bookpress
                    })
                    .Take(5)
                    .ToList();

                return Json(suggestions, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { error = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult ErrorPage()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetBookId(OrderInfo order)
        {
            order.OrderPrice = order.OrderAmount * order.OrderPrice;//计算价格 价格*数量

            var data = db.shopInfo.Where(m => m.Id == order.Id).FirstOrDefault();
            var capital = db.CapitalAdvance.Where(m => m.ShopId == order.Id).FirstOrDefault();
            if ( capital.Balance < order.OrderPrice)//客户账号余额<价格不库支
            {
                /*  TempData["BuyError"] = "余额不足，支付失败"; // 使用 TempData 传递错误信息
                  return View("ErrorPage"); */
                throw new Exception("这是一个测试异常！");
            }
            else
            {
                capital.Balance = capital.Balance - order.OrderPrice;
                Session["Balance"] = capital.Balance;
                var name = order.OrderName;
                PurchaseBook(order, data);
                AddCapitalAdvanceOrder(order, name);
                order.Id = 0;
                if (ModelState.IsValid)
                {
                    db.Entry(capital).State = EntityState.Modified;
                    db.SaveChanges();

                }
                if (ModelState.IsValid)
                {

                    db.OrderInfo.Add(order);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }

                return View();
            }

        }

        public ActionResult GetBookDetails(int? ID)
        {
            var data = db.BookDetailsInfo.Where(m => m.Id == ID).FirstOrDefault();
            return View(data);
        }


        /// <summary>
        ///添加账单记录
        /// </summary>
        /// <param name="order"></param>
        public void AddCapitalAdvanceOrder(OrderInfo order, string name)
        {
            var capital = new CapitalAdvanceOrder();
            var data = db.CapitalAdvance.Where(m => m.ShopId == order.Id).FirstOrDefault();
            capital.Code = order.OrderCode;
            capital.PayAmount = order.OrderPrice;
            capital.Balance = data.Balance;
            capital.ShopId = order.Id;
            capital.CreateTime = DateTime.Now;
            capital.BookName = name;
            if (ModelState.IsValid)
            {
                db.CapitalAdvanceOrder.Add(capital);
                db.SaveChanges();
            }
        }
        /// <summary>
        /// 字段填充
        /// </summary>
        /// <param name="order"></param>
        /// <param name="data"></param>
        public void PurchaseBook(OrderInfo order, shopInfo data)
        {
            if (order.OrderPrice == 0)
            {
                throw new NullReferenceException("请输入价格");
            }
            if (order.OrderAmount < 0)
            {
                throw new NullReferenceException("请输入购买数量");
            }
            order.OrderCode = "BOOK-" + DateTime.Now.ToString("yyyyMMddHHmmss");
            order.PayTime = DateTime.Now;
            order.ExpireTime = DateTime.Now.AddDays(10);
            order.OrderName = data.ShopName;
            order.OrderPhone = data.ShopPhone;


        }



        /// <summary>
        /// 查询账单
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ActionResult GetCapitalAdvanceOrdeR(int Id)
        {
            var data = db.CapitalAdvanceOrder.Where(m => m.ShopId == Id).ToList();
            return View(data);
        }


        public ActionResult AddCapitalAdvance(int Id)
        {
            // 存储 CapID 到 Session
            Session["CapID"] = Id;

            // 查询数据库
            var data = db.CapitalAdvance.FirstOrDefault(m => m.Id == Id+1);

            if (data == null)
            {
                // 可选：重定向到错误页面或创建新记录

                // 或者返回一个默认对象，避免视图报错
                data = new CapitalAdvance(); // 假设你的模型类是 CapitalAdvance
            }

            return View(data);
        }
        [HttpPost]
        public ActionResult AddCapitalAdvance(int Advance, int? id)
        {
            var capIdObj = Session["CapID"];
            if (capIdObj == null)
            {
                return RedirectToAction("Login"); // 或返回错误信息
            }

            int x = Convert.ToInt32(capIdObj);

            var capital = db.CapitalAdvance.FirstOrDefault(m => m.ShopId == x);
            if (capital == null)
            {
                capital = new CapitalAdvance
                {
                    ShopId = x,
                    Balance = Advance,
                    ReChargeAmount = Advance
                };
                db.CapitalAdvance.Add(capital);
            }
            else
            {
                capital.Balance += Advance;
                capital.ReChargeAmount += Advance;
                db.Entry(capital).State = EntityState.Modified;
            }

            if (ModelState.IsValid)
            {
                db.SaveChanges();
                return RedirectToAction("Actions", new { id = x });
            }

            return View(capital); // 返回视图并传入模型
        }


        public ActionResult Cancellation(int? Id)
        {
            var data = db.shopInfo.Where(m => m.Id == Id).FirstOrDefault();
            return View(data);
        }

        [HttpPost, ActionName("Cancellation")]
        [ValidateAntiForgeryToken]

        public ActionResult Cancellation(int Id)
        {
            var shop = db.shopInfo.Where(m => m.Id == Id).FirstOrDefault();
            var Order = db.OrderInfo.Where(m => m.OrderName == shop.ShopName).ToList();
            var Capita = db.CapitalAdvance.Where(m => m.ShopId == Id).FirstOrDefault();
            var CapitalAdvance = db.CapitalAdvanceOrder.Where(m => m.ShopId == Id).ToList();

            db.shopInfo.Remove(shop);
            db.OrderInfo.RemoveRange(Order);
            db.CapitalAdvance.Remove(Capita);
            db.CapitalAdvanceOrder.RemoveRange(CapitalAdvance);
            db.SaveChanges();
            return Redirect("https://localhost:44343/");


        }
            // GET: /BookDetailsInfo/Error
            public ActionResult Error()
            {
                return View();
            }


        // 添加带参数的构造函数用于测试
        public BookDetailsInfoController(BookcityEntities context)
        {
            db = context;
        }

        // 原始无参构造函数
        public BookDetailsInfoController() : this(new BookcityEntities())
        {
        }
    }
}
